package com.ly.feishu.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * 飞书消息
 *
 * @author LiuYang
 * @since 2025/8/14 22:23
 **/
@Service
public class FeishuMessageService {

    @Autowired
    private FeishuTokenService tokenService;
    @Autowired
    private FeishuUserService userService;
    @Value("${feishu.api.message-url}")
    private String MESSAGE_URL;

    private final RestTemplate restTemplate = new RestTemplate();
    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 发送应用消息卡片给指定用户（通过 Open ID）
     */
    public void sendPersonalCard(String mobile, String title, String content, String btnText, String btnUrl) {
        String token = tokenService.getTenantAccessToken();
        String url = MESSAGE_URL;

        String openId = userService.getOpenIdByMobile(mobile);
        // 构建消息卡片内容
        Map<String, Object> card = buildCard(title, content, btnText, btnUrl);

        try {
            // 1. 构建 content 对象
            String contentJson = objectMapper.writeValueAsString(card);
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("receive_id", openId);
            //requestBody.put("content", "{\"text\":\"test content\"}");
            //requestBody.put("msg_type", "text");
            requestBody.put("content", contentJson);
            requestBody.put("msg_type", "interactive");
            requestBody.put("receive_id_type", "open_id");

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.setBearerAuth(token);

            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
            ResponseEntity<String> response = restTemplate.postForEntity(url + "?receive_id_type=open_id", entity, String.class);

            if (response.getStatusCode() != HttpStatus.OK) {
                throw new RuntimeException("消息发送失败: " + response.getBody());
            }

            JsonNode respNode = objectMapper.readTree(response.getBody());
            if (respNode.get("code").asInt() != 0) {
                throw new RuntimeException("API 错误: " + respNode.get("msg").asText());
            }

        } catch (JsonProcessingException e) {
            throw new RuntimeException("JSON 序列化失败", e);
        }
    }

    private Map<String, Object> buildCard(String title, String content, String btnText, String btnUrl) {
        // config: {"wide_screen_mode": true}
        Map<String, Object> config = new HashMap<>();
        config.put("wide_screen_mode", true);

        // title: {"content": "新任务提醒", "tag": "plain_text"}
        Map<String, Object> titleMap = new HashMap<>();
        titleMap.put("content", title);
        titleMap.put("tag", "plain_text");

        // header: {"title": titleMap, "template": "blue"}
        Map<String, Object> header = new HashMap<>();
        header.put("title", titleMap);
        header.put("template", "blue");

        // text content: {"content": content, "tag": "lark_md"}
        Map<String, Object> textContent = new HashMap<>();
        textContent.put("content", content);
        textContent.put("tag", "lark_md");

        // text element: {"tag": "div", "text": textContent}
        Map<String, Object> textElement = new HashMap<>();
        textElement.put("tag", "div");
        textElement.put("text", textContent);

        // button text: {"content": btnText, "tag": "lark_md"}
        Map<String, Object> buttonText = new HashMap<>();
        buttonText.put("content", btnText);
        buttonText.put("tag", "lark_md");

        // button: {"tag": "button", "text": buttonText, "url": btnUrl, "type": "primary"}
        Map<String, Object> button = new HashMap<>();
        button.put("tag", "button");
        button.put("text", buttonText);
        button.put("url", btnUrl);
        button.put("type", "primary");

        // action: {"tag": "action", "actions": [button]}
        Map<String, Object> action = new HashMap<>();
        action.put("tag", "action");
        action.put("actions", new Object[]{button});

        // 最终卡片结构
        Map<String, Object> card = new HashMap<>();
        card.put("config", config);
        card.put("header", header);
        card.put("elements", new Object[]{textElement, action});

        return card;
    }
}
